package com.mall.common.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.commons.lang.StringUtils;

public class Pinyin4jUtils {
	public static String chineseToPinyin(String chinese) {
		if(StringUtils.isEmpty(chinese)) {
			throw new RuntimeException("参数不能为空！");
		}
		HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
		outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//发音第几声
		outputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
		StringBuilder pinyin = new StringBuilder();
		for(char ch : chinese.toCharArray()) {
			try {
				String[] letters = PinyinHelper.toHanyuPinyinStringArray(ch, outputFormat);
				if(letters != null && letters.length > 0) {
					pinyin.append(letters[0]);//数组形式返回是因为 中文存在多音字
				} else {
					pinyin.append(ch);
				}
			} catch (BadHanyuPinyinOutputFormatCombination e) {
				e.printStackTrace();
			}
		}
		return pinyin.toString();
	}
}
